//导航守卫:允许和不允许路由的通过，以及路由的引导
//导入路由
import router from '@/router'
import store from '@/store'
import { asyncRouter } from '@/router/asyncRouter'

//定义白名单:
const witeList = ['/login', '/register', '/404']

function getFirstMenuData(res) {
    const List = res.map(item => {
            return item.split(":")[0]
        })
        // console.log(List)
        // 去重返回数据
    return [...new Set(List)]
}

function getSecondMenuData(res) {
    const List = res.map(item => {
            return item.split(":")[0] + ":" + item.split(":")[1]
        })
        // console.log(List)
    return [...new Set(List)]
}

//匹配动态路由
function getRouterMatch(firstRouter, secondRouter, asyncRouter) {

    //处理超级管理员权限问题
    if (firstRouter.includes('*')) {
        return asyncRouter
    }

    // 先匹配一级路由，再在一级路由的基础上匹配二级路由
    // 1、匹配一级路由
    const List1 = asyncRouter.filter(item => {
            return firstRouter.includes(item.permission)
        })
        // console.log(List1)
    const List2 = List1.map(item1 => {
        return {
            ...item1,
            children: item1.children.filter(item2 => {
                return secondRouter.includes(item2.permission)
            })
        }
    })

    return List2

}

//导航守卫
router.beforeEach(
    async(to, from, next) => {
        // to:目标路由，表示要跳转到页面的路由
        // from:原路由
        // next:1.放行，2.引导跳转路由
        const token = store.state.user.token
            //如果token存在，跳转到首页    如果token不存在，跳转到登录页面
        if (token) {
            if (to.path == '/login') {
                next('/')
            } else {
                next() //next()中没有参数代表放行
                    //1.获取用户的权限数据
                    // const res = await getProfileAPI()
                    // console.log(res)

                const res = await store.dispatch('menu/getProfile') //异步函数中调用用dispatch
                    // console.log(res)
                    //2.处理数据['parking','park'] ['parking:rule','parking:rule']
                const firstMenuData = getFirstMenuData(res)
                const secondMenuData = getSecondMenuData(res)
                    // 过滤权限路由
                const routerMatch = getRouterMatch(firstMenuData, secondMenuData, asyncRouter)
                    // 把过滤好的权限路由添加到路由表中
                routerMatch.forEach(item => router.addRoute(item))
                    // 提供一份路由给vuex
                store.commit('menu/setmenuRouterList', routerMatch)
            }
        } else {
            if (witeList.includes(to.path)) {
                next()
            } else {
                next('/login')
            }
        }
    }
)